package com.slm.krstartimes.fragment;


import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.slm.krstartimes.R;
import com.slm.krstartimes.activity.MainActivity;
import com.slm.krstartimes.activity.NewsDetailActivity;
import com.slm.krstartimes.utils.L;
import com.slm.krstartimes.utils.SwipeRefreshLoadingLayout;
import com.slm.krstartimes.adapter.AndroidNewsAdapter;
import com.slm.krstartimes.adapter.ViewPagerAdapter;
import com.slm.krstartimes.db.sqlite.SQLiteDataBaseManager;
import com.slm.krstartimes.utils.News;
import com.slm.krstartimes.utils.NewsListSAX;
import com.slm.krstartimes.utils.SlideViewSAX;
import com.slm.krstartimes.utils.StreamRequest;

import org.xml.sax.SAXException;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;


/**
 * Created by dllo on 15/7/30.
 * Android
 */
public class AndroidHomeFragment extends android.support.v4.app.Fragment {
    private static final int TIME = 3000;
    List<String> list_focus;
    List<View> listViewDot;
    List<News> news;
    LayoutInflater inflater;
    private RequestQueue mQueue;
    private ListView androidNewsListview;
    private int currentPage = 0;
    private ViewPagerAdapter viewPargeAdapter;
    private ViewPager viewPager;
    private Runnable viewpagerRunnale;
    private Handler handler;
    private AndroidNewsAdapter newsAdapter;
    private ViewPagerAdapter viewPagerAdapter;
    private SwipeRefreshLoadingLayout srff;
    private Object data;
    private Runnable viewpagerRunnable;
    private ImageView[] imageViews;
    private ViewGroup vg;
    private FrameLayout frameLayout;
    private boolean flag = true;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.android_home_fragment, null);

        initView(inflater, view);

        refresh();

        return view;
    }

    /**
     * 刷新数据
     */
    private void refresh() {
        srff.setOnRefreshListener(new SwipeRefreshLoadingLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getList(System.currentTimeMillis() - 10 * 3600 * 1000);
                long time = System.currentTimeMillis();
                String str = Long.toString(time);
                Log.i("long", str);
            }

        });
        srff.setOnLoadListener(new SwipeRefreshLoadingLayout.OnLoadListener() {
            @Override
            public void onLoad() {
                getList(System.currentTimeMillis());
                Toast.makeText(getActivity(), "已是最后一条", Toast.LENGTH_SHORT).show();
                srff.setLoading(false);
            }
        });
    }

    /**
     * 初始化
     *
     * @param inflater
     * @param view
     */
    private void initView(LayoutInflater inflater, View view) {
        androidNewsListview = (ListView) view.findViewById(R.id.androidListview);
        srff = (SwipeRefreshLoadingLayout) view.findViewById(R.id.srff_android);
        View headview = inflater.inflate(R.layout.list_header, null);
        viewPager = (ViewPager) headview.findViewById(R.id.viewpager);
        androidNewsListview.addHeaderView(headview);
        frameLayout = (FrameLayout) view.findViewById(R.id.framlayout);
        vg = (ViewGroup) view.findViewById(R.id.vp);
        getList(System.currentTimeMillis() - 10 * 3600 * 1000);
    }

    /**
     * 获取网络数据
     *
     * @param time 当前系统时间
     */
    public void getList(long time) {
        StreamRequest request = new StreamRequest("http://api.ithome.com/xml/newslist/android.xml?r=" + time,

                new Response.Listener<InputStream>() {
                    /**
                     * 请求成功
                     * @param inputStream 返回流
                     */
                    @Override
                    public void onResponse(InputStream inputStream) {
                        handler = new Handler(new Handler.Callback() {
                            /**
                             * 接收解析完成的数据
                             * @param message
                             * @return
                             */
                            @Override
                            public boolean handleMessage(Message message) {
                                if (message.what == 10) {
                                    final List<News> list = (List<News>) message.obj;
                                    newsAdapter = new AndroidNewsAdapter(getActivity(), list);
                                    androidNewsListview.setAdapter(newsAdapter);
                                    srff.setRefreshing(false);
                                    Toast.makeText(getActivity(), "刷新成功", Toast.LENGTH_SHORT).show();
                                    MainActivity.sqLiteDataBaseTools.delete(SQLiteDataBaseManager.ANDROID);
                                    for (News news : list) {
                                        MainActivity.sqLiteDataBaseTools.insert(news.getNewsid(),
                                                news.getTitle(), news.getImage(), news.getHitcount(), news.getCommentcount(),
                                                SQLiteDataBaseManager.ANDROID);
                                    }
                                    androidNewsListview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                        /**
                                         * 列表监听
                                         * @param adapterView
                                         * @param view
                                         * @param i
                                         * @param l
                                         */
                                        @Override
                                        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                                            Intent newsDetail = new Intent(getActivity(), NewsDetailActivity.class);
                                            newsDetail.putExtra("newsId", list.get(i - 1).getNewsid());
                                            newsDetail.putExtra("title", list.get(i - 1).getTitle());
                                            newsDetail.putExtra("postdate", list.get(i - 1).getPostdate());
                                            newsDetail.putExtra("hitCount", list.get(i - 1).getHitcount());
                                            newsDetail.putExtra("image",list.get(i-1).getImage());
                                            startActivity(newsDetail);
                                        }
                                    });
                                }

                                return false;
                            }
                        });
                        Log.i("网络拉取成功", " android");
                        /**
                         * 解析数据
                         */
                        SAXParserFactory spx = SAXParserFactory.newInstance();
                        try {
                            SAXParser sp = spx.newSAXParser();
                            sp.parse(inputStream, new NewsListSAX(handler));

                        } catch (ParserConfigurationException e) {
                            e.printStackTrace();
                        } catch (SAXException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            /**
             * 请求失败,从数据库读取数据
             * @param volleyError
             */
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Toast.makeText(getActivity(), "刷新失败", Toast.LENGTH_SHORT).show();
                srff.setRefreshing(false);
                List<News> list = MainActivity.sqLiteDataBaseTools.query(SQLiteDataBaseManager.ANDROID);
                newsAdapter = new AndroidNewsAdapter(getActivity(), list);
                androidNewsListview.setAdapter(newsAdapter);
            }
        });
        MainActivity.requestQueue.add(request);
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        //assignment();
        Log.i("轮播图", "开始轮播");
        getData();

        initListener();

    }

    /**
     * 轮播
     */
    private void initListener() {
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            boolean isScrolled = false;


            public void onPageScrollStateChanged(int status) {
                switch (status) {
                    case 1:// 手势滑动
                        isScrolled = false;
                        break;
                    case 2:// 界面切换
                        isScrolled = true;
                        break;
                    case 0:// 滑动结束

                        // 当前为最后一张，此时从右向左滑，则切换到第一张
                        if (viewPager.getCurrentItem() == viewPager.getAdapter()
                                .getCount() - 1 && !isScrolled) {
                            viewPager.setCurrentItem(0);
                        }
                        // 当前为第一张，此时从左向右滑，则切换到最后一张
                        else if (viewPager.getCurrentItem() == 0 && !isScrolled) {
                            viewPager.setCurrentItem(viewPager.getAdapter()
                                    .getCount() - 1);
                        }
                        break;
                }


            }


            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            public void onPageSelected(int index) {


            }
        });

    }

    /**
     * 开启z子线程通知viewpager自动播放
     */
    protected void initRunnable(final int size) {

        viewpagerRunnable = new Runnable() {
            @Override
            public void run() {
                int nowIndex = viewPager.getCurrentItem();

                // 如果下一张的索引大于最后一张，则切换到第一张
                if (nowIndex + 1 >= size) {
                    viewPager.setCurrentItem(0);
                } else {
                    viewPager.setCurrentItem(nowIndex + 1);
                }
                handler.postDelayed(viewpagerRunnable, TIME);
            }
        };
        handler.postDelayed(viewpagerRunnable, TIME);
    }

    /**
     * 请求轮播数据
     */
    public void getData() {

        StreamRequest request = new StreamRequest("http://api.ithome.com/xml/slide/android.xml",

                new Response.Listener<InputStream>() {
                    @Override
                    public void onResponse(InputStream inputStream) {
                        L.i("android拉取成功"+inputStream);
                        handler = new Handler(new Handler.Callback() {
                            @Override
                            public boolean handleMessage(Message message) {
                                if (message.what == 200) {
                                    final List<News> list = (List<News>) message.obj;
                                    viewPagerAdapter = new ViewPagerAdapter(getActivity(), list);
                                    viewPager.setAdapter(viewPagerAdapter);
                                    if (flag) {
                                        initRunnable(list.size());
                                        flag = false;
                                    }
                                    MainActivity.sqLiteDataBaseTools.delete(SQLiteDataBaseManager.ANDROID);
                                    for (News news : list) {
                                        MainActivity.sqLiteDataBaseTools.insert(news.getNewsid(),
                                                news.getTitle(), news.getImage(), news.getHitcount(), news.getCommentcount(),
                                                SQLiteDataBaseManager.ANDROID);
                                    }
                                    viewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
                                        @Override
                                        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                                        }

                                        /**
                                         * 设置圆点
                                         * @param position
                                         */
                                        @Override
                                        public void onPageSelected(int position) {
                                            currentPage = position;
                                            for (int i = 0; i < list.size(); i++) {
                                                if (i == position) {
                                                    imageViews[i]
                                                            .setBackgroundResource(R.mipmap.point_blue);
                                                } else {
                                                    imageViews[i]
                                                            .setBackgroundResource(R.mipmap.point);
                                                }
                                            }
                                        }
                                    });

                                    imageViews = new ImageView[list.size()];
                                    ImageView imageView;
                                    for (int i = 0; i < list.size(); i++) {
                                        imageView = new ImageView(getActivity());
                                        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(20, 20);
                                        layoutParams.setMargins(8, 0, 8, 0);
                                        imageView.setLayoutParams(layoutParams);
                                        imageViews[i] = imageView;
                                        if (i == 0) {
                                            imageViews[i]
                                                    .setBackgroundResource(R.mipmap.point_blue);
                                        } else {
                                            imageViews[i]
                                                    .setBackgroundResource(R.mipmap.point);
                                        }
                                        vg.addView(imageViews[i]);
                                        viewPager.setOnClickListener(new AdapterView.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {

                                            }

                                        });
                                    }
                                }
                                return false;
                            }
                        });
                        SAXParserFactory spx = SAXParserFactory.newInstance();
                        try {
                            SAXParser sp = spx.newSAXParser();
                            sp.parse(inputStream, new SlideViewSAX(handler));

                        } catch (ParserConfigurationException e) {
                            e.printStackTrace();
                        } catch (SAXException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Toast.makeText(getActivity(), "加载失败", Toast.LENGTH_SHORT).show();
                L.i("android拉取失败"+volleyError);
                List<News> list = MainActivity.sqLiteDataBaseTools.query(SQLiteDataBaseManager.ANDROID);
                newsAdapter = new AndroidNewsAdapter(getActivity(), list);
                androidNewsListview.setAdapter(newsAdapter);
            }
        });
        MainActivity.requestQueue.add(request);

    }


}





